<template>
  <el-select
    v-model="localKeys"
    @change="updateValue"
    clearable
    filterable
    multiple
    collapse-tags
    collapse-tags-tooltip
    v-bind="attrs"
  >
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item" />
  </el-select>
</template>
<script setup lang="ts">
import { onMounted, ref, useAttrs, watch } from 'vue'
import { getRegionOptions } from '@/api/common'

const options = ref([
  {
    label: '请选择',
    value: '',
  },
])
const attrs = useAttrs()
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
})
// 本地维护选中的key数组
const localKeys = ref<string[]>([...props.modelValue])
const emits = defineEmits(['update:modelValue'])

// 当选中值变化时，对外发射key数组
const updateValue = (values: string[]) => {
  emits('update:modelValue', values)
}

// 监听外部v-model变化，同步到本地
watch(
  () => props.modelValue,
  (newVal) => {
    localKeys.value = [...newVal]
  },
  { deep: true }
)

const regionOptions = () => {
  return getRegionOptions().then((res) => {
    options.value = res.data
  })
}

onMounted(() => {
  regionOptions()
})
</script>
<style scoped lang="scss"></style>
